import { Snake } from "./Snake";
import { Food } from "./Food";
import { ScorePanel } from "./ScorePanel";
//游戏控制器
export class GameControl{
    //定义属性
    snake:Snake;//蛇
    food:Food;//食物
    scorePanel:ScorePanel;//记分牌
    //创建一个属性来储存蛇的移动方向（也就是按键的方向）
    direction:string = '';
    //记录游戏是否结束
    isLive = true;
    constructor(){
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel(10,2)
        this.init()
    }
    init(){
        //绑定键盘事件
        document.addEventListener('keydown',this.keydownHandler.bind(this))
        this.run()
    }
    //创建键盘响应函数
    keydownHandler(e:KeyboardEvent){
        // console.log(e.key);
        //ArrowUp ArrowDown ArrowLeft ArrowRight
        //检测值的合法性
        this.direction = e.key;
        // this.run()
    }
    //控制蛇移动的方法
    run(){
        //上下左右
        let x = this.snake.x;
        let y = this.snake.y;
        switch(this.direction){
            case "ArrowUp":
            case "w":
                y -=10;
                break;
            case "ArrowDown":
            case "s":
                y +=10;
                break;
            case "ArrowLeft":
            case "a":
                x -=10;
                break;
            case "ArrowRight":
            case "d":
                x +=10;
                break;
        }
        //检查蛇是否吃到食物
        this.checkEat(x,y)
        //修改
        try {
            this.snake.x = x;
            this.snake.y = y;
        } catch (error) {
            //异常处理
            alert((error as Error).message + 'GAME OVER!')
            this.isLive = false
        }
        this.isLive && setTimeout(() => {
            this.run()
        }, 500-(this.scorePanel.level-1)*50);
    }
    //检查蛇是否吃到食物方法
    checkEat(x:number,y:number):void{
         if(x === this.food.x && y === this.food.y){
            // console.log("chidaole");
            //重置
            this.food.change()
            //加分
            this.scorePanel.addScore();
            //加身体
            this.snake.addBody()
         }
    }

}